/**
 * 
 */
package com.hw.hcit.feature;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.NoCopySpan.Concrete;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;


/**
 * @author gaoshengpan
 *
 */
public class HeadsetLoopbackTestItem extends JTestItem {
	private TextView textView1, textView2;
    private Button mButton;
    private boolean inRecord = false;
    private boolean started = false;
    private MediaRecorder mMediaRecorder ;
    private Context mContext;
    private AudioManager mAudioManager;
    private String mAudiofilePath;
    private boolean isRecording = false;
    private String TAG = "HeadsetLoopbackTestItem";
    private boolean tested = false;
    private boolean powerClicked = false;
    private Button mButton1,mButton2;
   private static MediaPlayer mMediaPlayer ;
 
    /**
     * @param cb
     */
    public HeadsetLoopbackTestItem(JCtrlCallback cb) {
        super(cb);
        // TODO Auto-generated constructor stub
    }
    

    /**
     * 
     */
    public HeadsetLoopbackTestItem() {
        // TODO Auto-generated constructor stub
    }

   @Override
   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      mContext = Config.GetActivity();
      mAudioManager = (AudioManager) mContext
            .getSystemService(Context.AUDIO_SERVICE);
      /*
       * if(!mAudioManager.isWiredHeadsetOn()){
       * showWarningDialog(getString(R.string.insertheadset)); }
       */
   }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.headsetloopback_test,
                container, false);
        textView1 = (TextView) rootView.findViewById(R.id.textView1);
        textView2 = (TextView) rootView.findViewById(R.id.textView2);
        mButton = (Button) rootView.findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!started) {
                    Log.d(TAG, "onClick------------>onClick0");
                    started = true;
                    textView1.setText(getString(R.string.recording));
                    mButton.setText(getString(R.string.toplay));
                    mButton.setEnabled(false);
                    inRecord();
                } else {
                    if (mButton.getText() == getString(R.string.toplay)) {
                        Log.d(TAG, "onClick------------>onClick1");
                        // in play
                        textView1.setText(getString(R.string.playing));
                        mButton.setText(getString(R.string.torecord));
                        mButton.setEnabled(false);
                        inPlay();
                        
                    } else {
                        // in record
                        Log.d(TAG, "onClick------------>onClick2");
                        
                        textView1.setText(getString(R.string.recording));
                        mButton.setText(getString(R.string.toplay));
                        mButton.setEnabled(false);
                        inRecord();
                        
                        
                    }
                }
            }
        });
        mButton1 = (Button) rootView.findViewById(R.id.button2);
		mButton2 = (Button) rootView.findViewById(R.id.button3);
		mButton1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(18, 'P');
					} else {
						rewriteOneByteOfNv2499(49, 'P');
					}
				}
				 testFinish(true, 1, true);
				
			}
		});
		mButton2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(18, 'F');
					} else {
						rewriteOneByteOfNv2499(49, 'F');
					}
				}
				testFinish(false, 1, false);
				
			}
		});
        return rootView;
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub\
//        Settings.Global.putInt(mContext.getContentResolver(), "headsetloop_test_running", 1);
        super.onResume();
        /*gaoshenpan 15-08-24 fix no WiredHeadset to record begin*/
        /*15-12-24 gaoshenpan fix open mic to protect Running Crash&&closeMic begin */
        mAudioManager.setMicrophoneMute(false);
        /*15-12-24 gaoshenpan fix open mic to protect Running Crash&&closeMic end */
        IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_HEADSET_PLUG);
		mContext.registerReceiver(mReceiver, filter);
		/*15-10-20 gaoshenpan fix create mMediaRecorder&mMediaPlayer  begin*/
        if (mMediaRecorder == null) {
            Log.d(TAG, "onResume()-----mMediaRecorder == null");
            mMediaRecorder = new MediaRecorder();
        }else{
            Log.d(TAG, "onResume()-----mMediaRecorder != null");
        }
        
        if (mMediaPlayer == null) {
            Log.d(TAG, "onResume()-----mMediaPlayer == null");
            mMediaPlayer = new MediaPlayer();
        }else{
            Log.d(TAG, "onResume()-----mMediaPlayer != null");
        }
        /*15-10-20 gaoshenpan fix create mMediaRecorder&mMediaPlayer  end*/
        mButton.setEnabled(true);
        mButton1.setEnabled(false);
        mButton2.setEnabled(false);
        tested = false;
		powerClicked = false;
        if(!mAudioManager.isWiredHeadsetOn()){
        	mButton.setEnabled(false);
            showWarningDialog(getString(R.string.insertheadset));
        }
        inRecord = false;
        textView1.setText(getString(R.string.headmic_test));
        mButton.setText(getString(R.string.torecord));
    }
    
	BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				if (intent.getIntExtra("state", 0) == 0) {
					mButton.setEnabled(false);
					 showWarningDialog(getString(R.string.insertheadset));
				} else {
					mButton.setEnabled(true);
				}
			
			} 
		}
	};
	 /*gaoshenpan 15-08-24 fix no WiredHeadset to record end*/

	/*15-10-20 gaoshenpan deal with mMediaRecorder&mMediaPlayer onPause&onStop&onDestroy begin*/
	 @Override
	    public void onPause() {
	        // TODO Auto-generated method stub
	        super.onPause();
	        Log.d(TAG, "onPause()");
	        mContext.unregisterReceiver(mReceiver);
	        if (isRecording && mMediaRecorder != null) {
	            mMediaRecorder.stop();
	            mMediaRecorder.release();
	            mMediaRecorder = null;
	            mHandler.removeMessages(0);
	            Log.d(TAG, "------onPause----1-----");
	        }
	        if (mMediaPlayer == null) {
	            Log.d(TAG, "------onPause----mMediaPlayer-----null");
	        }
	        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
	            mMediaPlayer.stop();
	            Log.d(TAG, "------onPause----mMediaPlayerstop-----");
	            mMediaPlayer.release();
	            mMediaPlayer = null;
	            Log.d(TAG, "------onPause----mMediaPlayerRelease-----");
	        }
	    }
	 
	   @Override
	    public void onStop() {
	        // TODO Auto-generated method stub
	        super.onStop();
	        Log.d(TAG, "onStop()");
	        if (isRecording && mMediaRecorder != null) {
	            mMediaRecorder.stop();
	            mMediaRecorder.release();
	            mMediaRecorder = null;
	            Log.d(TAG, "------onStop----1-----");
	        }

	    }
	   @Override
	   public void onDestroy() {
	       // TODO Auto-generated method stub
	       super.onDestroy();
	       Log.d(TAG, "onDestroy()");
	       if(mMediaRecorder != null){
	       	mMediaRecorder.release();
	           mMediaRecorder = null;
	           Log.d(TAG, "------onDestroy----1-----");
	       }
	       if (mMediaPlayer != null) {
	           mMediaPlayer.stop();
	           Log.d(TAG, "------onDestroy----mMediaPlayerstop-----");
	           mMediaPlayer.release();
	           mMediaPlayer = null;
	           Log.d(TAG, "------onDestroy----mMediaPlayerRelease-----");
	       }
	   }
	   /*15-10-20 gaoshenpan deal with mMediaRecorder&mMediaPlayer onPause&onStop&onDestroy end*/


    public void inRecord() {

        
        if (mAudioManager.isWiredHeadsetOn()) {

         try {
            if (Environment.getExternalStorageState().equals(
                  android.os.Environment.MEDIA_MOUNTED)) {
               Log.d(TAG,
                     "Environment.getExternalStorageState()------------>"
                           + Environment.getExternalStorageState());
            }
            record();
            isRecording = true;

            mHandler.sendEmptyMessageDelayed(0, 2500);
         } catch (Exception e) {
            loge(e);
         }
      } else {  
         showWarningDialog(getString(R.string.insertheadset));
      }
   }

    public void inPlay() {
        mButton.setEnabled(false);
        mButton.setText(getString(R.string.torecord));
        try {
            replay();
           
        } catch (Exception e) {
            loge(e);
        }

    }
    
    void showWarningDialog(String title) {
    	 /*gaoshenpan 15-08-24 fix no WiredHeadset to record begin*/
    	   Log.d(TAG,
                   "showWarningDialog(String title)------------>"
                         + "0");

        new AlertDialog.Builder(mContext)
                .setTitle(title)
                .setPositiveButton(getString(R.string.ok),
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {
                                if(!mAudioManager.isWiredHeadsetOn()){
                                	   Log.d(TAG,
                                               "showWarningDialog(String title)------------>"
                                                     + "1");
                                	 showWarningDialog(getString(R.string.insertheadset));
                                }else{
                                	Log.d(TAG,
                                            "showWarningDialog(String title)------------>"
                                                  + "2");
                                	mButton.setEnabled(true);
                                }
                                /*gaoshenpan 15-08-24 fix no WiredHeadset to record end*/
                            }
                            
                        }).show();

   }

   void record() throws IllegalStateException, IOException,
         InterruptedException {
	   /*15-10-20 gaoshenpan deal with mMediaRecorder in record() begin*/
      if (mMediaRecorder != null) {
         Log.d(TAG, "------------>mMediaRecorder!=null");
            mMediaRecorder.reset();
        }else{
        	mMediaRecorder = new MediaRecorder();
      }
      mButton1.setEnabled(false);
      mButton2.setEnabled(false);
      mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
      mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
      mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
            @Override
            public void onError(MediaRecorder mediarecorder, int arg1, int arg2) {
                // TODO Auto-generated method stub
                Log.d(TAG, "------->" + "mMediaRecorder===onError");
                if (mediarecorder != null && isRecording) {
                    Log.d(TAG, "------->" + "mMediaRecorder===xxxxxxx");
                    mediarecorder.stop();
                    mediarecorder.release();
                    mediarecorder = null;
                }
            }
        });
        /*15-10-20 gaoshenpan deal with mMediaRecorder in record() end*/
      // Environment.setUserRequired(false);
      mMediaRecorder.setOutputFile("storage/sdcard0/"
            + "/testHeadset.amr");
      mAudiofilePath = "storage/sdcard0/" + "/testHeadset.amr";
      Log.d(TAG, "path------------>"
            + Environment.getExternalStorageDirectory().toString());
      mMediaRecorder.prepare();
      mMediaRecorder.start();
   }

   void replay() throws IllegalArgumentException, IllegalStateException,
         IOException {
      textView1.setText(getString(R.string.playing));
      mButton.setEnabled(false);
      File file = new File(mAudiofilePath);
      FileInputStream mFileInputStream = new FileInputStream(file);
      /*15-09-24 gaoshenpan fix can not play begin*/
        /*15-10-20 gaoshenpan fix mMediaPlayernot play  begin*/
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            Log.d(TAG, "replay()-----mMediaPlayer != null");
        } else {
            mMediaPlayer = new MediaPlayer();
            Log.d(TAG, "replay()-----mMediaPlayer == null");
        }

        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer player, int arg1, int arg2) {
                // TODO Auto-generated method stub
                if (player != null && player.isPlaying()) {
                    Log.d(TAG, "------->" + "onError====mMediaPlayer");
                    player.stop();
                    Log.d(TAG, "------->" + "onError====mMediaPlayer---stop()");
                    player.release();
                    Log.d(TAG, "------->"
                            + "onError====mMediaPlayer---release()");
                    player = null;
                    Log.d(TAG, "------->"
                            + "onError====mMediaPlayer---release()");
                }
                Log.d(TAG, "------->" + "onError");
                return false;
            }
        });
        /* 15-09-24 gaoshenpan fix can not play end */
        mMediaPlayer.setDataSource(mFileInputStream.getFD());
        mMediaPlayer.prepare();
        mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.d(TAG, "------->" + "onPrepared");
                mp.start();
                Log.d(TAG, "------->" + "onPrepared1");
            }
        });

        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mPlayer) {

                Log.d(TAG, "------->" + "onCompletion");
                Log.d(TAG, "------->" + "onCompletion===1111111");
                mPlayer.stop();
                Log.d(TAG, "------->" + "onCompletion===stop()");
                File file = new File(mAudiofilePath);
                file.delete();
                mHandler.sendEmptyMessage(1);
              /*  mButton.setEnabled(true);
                textView1.setText(getString(R.string.played));*/

                /*if (!mFinished) {
                    showConfirmDialog();
                }*/

            }
        });

    }

    private void loge(Object e) {

        if (e == null)
            return;
        Thread mThread = Thread.currentThread();
        StackTraceElement[] mStackTrace = mThread.getStackTrace();
        String mMethodName = mStackTrace[3].getMethodName();
        e = "[" + mMethodName + "] " + e;
        Log.e(TAG, e + "");
    }

    
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            /*if(!mAudioManager.isWiredHeadsetOn()){
                showWarningDialog(getString(R.string.insertheadset));
            }*/
            Log.d(TAG, "mhandle------------>");
            switch (msg.what) {

	         case 0:
	            /*15-10-20 gaoshenpan fix judge begin */
	            if (isRecording && mMediaRecorder !=null) {
	               /*15-10-20 gaoshenpan fix judge begin */
	               Log.d(TAG, "mhandle------------>recorded");
	               mMediaRecorder.stop();

                    isRecording = false;
                    mButton.setEnabled(true);
                    textView1.setText(getString(R.string.recorded));
                    /*try {
                        replay();
                    } catch (Exception e) {
                        Log.e(TAG, "Exception e------>"+e.toString());
                    }*/
                } 
                break;
            /*case 1:
                textView1.setText(getString(R.string.recorded));
                mButton.setEnabled(true);
                break;*/
            case 1:
                Log.d(TAG, "mhandle------------>played");
                textView1.setText(getString(R.string.played));
                tested = true;
                mButton1.setEnabled(true);
                mButton2.setEnabled(true);
                mButton.setEnabled(true);
                break;
            default:
                break;
            }
        }
    };
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        return true;
    }

    /*@Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            dissmissPowerClicked();
            Log.d(TAG, " --------->KeyEvent.KEYCODE_VOLUME_DOWN");
            if (powerClicked) {
                Log.d(TAG,
                        "powerClicked --------->KeyEvent.KEYCODE_VOLUME_DOWN");
                testFinish(false, 1, false);
                return true;
            }
            if (tested) {
                Log.d(TAG,
                        "tested --------->KeyEvent.KEYCODE_VOLUME_DOWN");
                testFinish(true, 1, true);
            } else {
                Log.d(TAG, " --------->showTestUncomplete");
                showTestUncomplete();
            }
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            dissmissPowerClicked();
            testFinish(true, -1, true);
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
            Log.d(TAG, "powerClicked --------->KeyEvent.KEYCODE_POWER");
            powerClicked = true;
            showPowerClicked();
        }
        return true;
    }
*/


}
